/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	/**
	 * 15
	 **/
	 		function rando(m) {
	  var num = '';
	  for(var i = 0; i < m; i++) {
	    var val = parseInt(Math.random()*10, 10);
	    if(i === 0 && val === 0) {
	      i--;
	      continue;
	 }
	 num += val;
	 }
	 return num;
	 };
	 
	 /**
	  * 用户登录
	  **/
	owner.login = function(loginInfo, callback) {
		callback = callback || $.noop;
		loginInfo = loginInfo || {};
		loginInfo.account = loginInfo.account || '';
		loginInfo.password = loginInfo.password || '';
		if (loginInfo.account.length <=0) {
			return callback('同学请输入学号');
		}
		if (loginInfo.password.length <=0) {
			return callback('同学请输入学号');
		}

		 loginInfo.Method='Login';		
		$.ajax(owner.server,{
			//服务器地址
    	url:'http://kc.gxxd.net.cn/suite/android/login.do?' ,
        data:{
		loginName: loginInfo.account,
		password:  loginInfo.password,
		imeiCode : rando(15),
		APPversion : '1.2',
		appLanguage :'android'
        },     
	  dataType:'json',
	     //服务器返回json格式数据  
			type:'get',
	 		     //HTTP请求类型
			timeout:2000,
		//超时时间设置为2秒；
			success:function(data){		
            if(data.bindStatus==3){		
			 plus.nativeUI.alert('(・ω |   '+ data.userName+ '你好呀 ~ (*/ω＼*) \n mark> 自行识别 \n mark> 应用执行第2套储取 \n mark> 请在退出应用重开 \n mark> 并开启自动登陆 \n mark> 相关方案运行已采集   \n mark> 将用于下个版本将更新新的储取方案');

			    // mui.toast("json:::" +data.userKey ); 
			   var userKeyid =data.userKey;
			   var userNameid = data.userName;
			   localStorage.setItem( 'userKey', userKeyid );
			    localStorage.setItem( 'userNameid', userNameid );
			   var keysss = localStorage.getItem( 'userKey');
			   var namess =  localStorage.getItem( 'userNameid');
			    console.log("1:"+keysss);
				console.log("1:"+namess);
               return owner.createState(loginInfo.account, callback ); 
				ate.isLogin=true;//标记已登录
                state.user=data.Data;//保存用户信息
                owner.setState(state);
				
			   
			   
 
			   	//var myItem = localStorage.getItem( user );
			   	//mui.toast("json:::" + keys ); 
				//保存登录信息
                localStorage.setItem('$user', JSON.stringify(loginInfo));
				var data = {column: "bindStatus,userKey,userName",
				//需要的字段名{"identity":"student","bindStatus":"3","userKey":"12111","userName":"黄忠庆"}
                           }
              //通知资金变动页面刷新
                var moneyChange=plus.webview.getWebviewById('moneyChange');
                if(moneyChange){
                    mui.fire(moneyChange,'show');
                    
                }
                //通知其他用户相关页面更新
             
			   }
            else
				{
					
			return callback( loginInfo.account+'学号  你的密码错误，请核对后重新输入！');	
							
				
				}
				
				
        },
        error:function(xhr,type,errorThrown){
            mui.alert('恭喜学号'+loginInfo.account+'\n'+'网络延时,请重新加载 O(∩_∩)O~ \n' , '断网通知' );
        } 
    });
};
			
			
/*		var users = JSON.parse(localStorage.getItem('$users') || '[]');
		var authed = users.some(function(user) {
			return loginInfo.account !== user.account && loginInfo.password !== user.password;
		});
		if (authed) {
			return owner.createState(loginInfo.account, callback);
		} else {
			return callback('用户名或密码错误');
		}
	};*/

	owner.createState = function(name, callback) {
		var state = owner.getState();
		state.account = name;
		state.token = "token123456789";
		owner.setState(state);
		return callback();
	};




	/**
	 * 新用户注册
	 **/
	owner.reg = function(regInfo, callback) {
		callback = callback || $.noop;
		regInfo = regInfo || {};
		regInfo.account = regInfo.account || '';
		regInfo.password = regInfo.password || '';
		if (regInfo.account.length < 5) {
			return callback('用户名最短需要 5 个字符');
		}
		if (regInfo.password.length < 6) {
			return callback('密码最短需要 6 个字符');
		}
		if (!checkEmail(regInfo.email)) {
			return callback('邮箱地址不合法');
		}
	
	
		var users = JSON.parse(localStorage.getItem('$users') || '[]');
		users.push(regInfo);
		localStorage.setItem('$users', JSON.stringify(users));
		return callback();
	};


	/**
	 * 获取当前状态
	 **/
	owner.getState = function() {
		var stateText = localStorage.getItem('$state') || "{}";
		return JSON.parse(stateText);
	};


	/**
	 * 设置当前状态
	 **/
	owner.setState = function(state) {
		state = state || {};
		localStorage.setItem('$state', JSON.stringify(state));
		//var settings = owner.getSettings();
		//settings.gestures = '';
		//owner.setSettings(settings);
	};

	var checkEmail = function(email) {
		email = email || '';
		return (email.length > 3 && email.indexOf('@') > -1);
	};


	/**
	 * 找回密码
	 **/
	owner.forgetPassword = function(email, callback) {
		callback = callback || $.noop;
		if (!checkEmail(email)) {
			return callback('邮箱地址不合法');
		}
		return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
	};


	/**
	 * 获取应用本地配置
	 **/
	owner.setSettings = function(settings) {
		settings = settings || {};
		localStorage.setItem('$settings', JSON.stringify(settings));
	}


	/**
	 * 设置应用本地配置
	 **/
	owner.getSettings = function() {
			var settingsText = localStorage.getItem('$settings') || "{}";
			return JSON.parse(settingsText);
		}
		
		
		/**
		 * 获取本地是否安装客户端
		 **/
	owner.isInstalled = function(id) {
		if (id === 'qihoo' && mui.os.plus) {
			return true;
		}
		if (mui.os.android) {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager)
			var packageName = {
				"qq": "com.tencent.mobileqq",
				"weixin": "com.tencent.mm",
				"sinaweibo": "com.sina.weibo"
			}
			try {
				return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
			} catch (e) {}
		} else {
			switch (id) {
				case "qq":
					var TencentOAuth = plus.ios.import("TencentOAuth");
					return TencentOAuth.iphoneQQInstalled();
				case "weixin":
					var WXApi = plus.ios.import("WXApi");
					return WXApi.isWXAppInstalled()
				case "sinaweibo":
					var SinaAPI = plus.ios.import("WeiboSDK");
					return SinaAPI.isWeiboAppInstalled()
				default:
					break;
			}
		}
	}
}(mui, window.app = {}));